package com.example.capsule_netty.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.example.capsule_netty.bean.SignBean;
import com.example.capsule_netty.configuration.Constant;
import com.example.capsule_netty.mapper.SignMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @Author: zhuzhiming
 * @Date: 2022/5/20 17:06
 */
@Service
public class SignService {
    @Resource
    SignMapper signMapper;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    public String doJudgeHasSign(String roomName, String userId) {

        SignBean signBean = new SignBean();
        String key = roomName + "-sign";
        String endTime = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(endTime)) {
            signBean.setSignStatus(2);
        } else {
            QueryWrapper<SignBean> queryWrapper = new QueryWrapper<SignBean>().eq("room_name", roomName).eq("sender_id", userId);
            List<SignBean> signBeanList = signMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(signBeanList) || signBeanList.get(0).getSignStatus() == 0) {
                signBean.setSignStatus(0);
            } else {
                signBean = signBeanList.get(0);
            }
        }
        return new Gson().toJson(signBean);
    }

    public String doSign(SignBean signBean) {
        if (signBean.getSignStatus() == 0) {
            signBean.setSignStatus(1);
            signMapper.insert(signBean);
        } else {
            signMapper.updateById(signBean);
        }
        return Constant.SUCCESS;
    }
}
